package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.vo.OrderSubmitParam;
import io.swagger.annotations.Api;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
import java.util.*;

/**
 * @author spt
 * @description 预约设置控制器
 * @date
 **/
@RestController
@RequestMapping("/ordersetting")
@Slf4j
@Api(tags = "后台预约设置接口")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 预约Excel文件上传
     * @param multipartFile
     */
    @PostMapping("upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile){
        log.info("完成excel文件上传{}",multipartFile);
        String fileName = multipartFile.getOriginalFilename();
        //对上传的文件名进行判断
        if (StringUtils.isEmpty(fileName)){
            return new Result(false,MessageConst.ACTION_FAIL);
        }
        Workbook workbook = null;//从excel表中读取数据
        try{
            InputStream is = multipartFile.getInputStream();
            //对上传文件进行判断
            if(fileName.endsWith(".xls")){
              workbook = new HSSFWorkbook(is);
            }else if (fileName.endsWith(".xlsx")){
                workbook = new XSSFWorkbook(is);
            }else {
                return new Result(false,"您传入的文件格式不正确");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"文件上传失败");
        }
        //首先遍历文件取数据
        List<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet rows : workbook) {
            for (int i = 1; i < rows.getLastRowNum(); i++) {
                //在excel表中，第一行是表头，所以取数据要从第一行取
                Row row = rows.getRow(i);//代表行
                OrderSetting orderSetting = getColumn(row);//获取列单独写一个方法
                orderSettings.add(orderSetting);//将列添加到orderSettings表中
            }
        }
        log.info("上传成功{}",orderSettings);
        orderSettingService.uploadExcel(orderSettings);
        return new Result(true,MessageConst.UPLOAD_SUCCESS);
    }
    private OrderSetting getColumn(Row row){
        //列中两个数据先设置为空，向里面加数据
        Date date =null;
        Integer number = null;
        try{
            if (row.getCell(0)!=null){//日期不能为空
                date = row.getCell(0).getDateCellValue();
            }
           if (row.getCell(1)!=null){//可预约数量不为空 写入可预约数据列
               double num = row.getCell(1).getNumericCellValue();
               number = Double.valueOf(num).intValue();//将可预约数量转换为int类型
           }
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessRuntimeException(String.format("数据格式有误"));
        }
        if (date == null || number == null){
            throw new BusinessRuntimeException(String.format("缺少数据"));
        }
        return new OrderSetting(date,number);
    }



    /**
     * 体检预约-基于日历实现预约设置
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
    }

    // 5 预约管理之当月预约信息展示
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam String year, @RequestParam String month) {
        //查询数据
        List<OrderSetting> orderSettings = orderSettingService.getOrderSettingByMonth(year, month);
        //转换成前端需要的结构
        List<Map<String, Object>> List = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            //创建用于日期处理的工具类Calendar对象
            Calendar cal = Calendar.getInstance();
            //设置时间为预约日期
            cal.setTime(orderSetting.getOrderDate());
            Map<String, Object> map = new HashMap<>();
            //设置日期限-当月第几天
            map.put("date", cal.get(Calendar.DAY_OF_MONTH));
            //设置数量-当天允许的预约数量
            map.put("number", orderSetting.getNumber());
            //设置已经预约的人数
            map.put("reservations", orderSetting.getReservations());
            //将拿到的内容传到集合中
            List.add(map);
        }
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS,List);
    }


}
